package com.agriculture.competition.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.agriculture.common.core.utils.DateUtils;
import com.agriculture.common.core.utils.StringUtils;
import com.agriculture.competition.config.MinioConfig;
import com.agriculture.competition.domain.JaClassify;
import com.agriculture.competition.domain.JaDateTable;
import com.agriculture.competition.domain.JaExcelClassify;
import com.agriculture.competition.domain.JaFile;
import com.agriculture.competition.domain.vo.*;
import com.agriculture.competition.enums.Classify;
import com.agriculture.competition.mapper.JaClassifyMapper;
import com.agriculture.competition.mapper.JaDateTableMapper;
import com.agriculture.competition.mapper.JaExcelClassifyMapper;
import com.agriculture.competition.mapper.JaFileMapper;
import com.agriculture.competition.service.IJaDateTableService;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据管理Service业务层处理
 *
 * @author agriculture
 * @date 2024-11-12
 */
@Service
@Slf4j
public class JaDateTableServiceImpl implements IJaDateTableService {

    @Autowired
    private JaDateTableMapper jaDateTableMapper;
    @Autowired
    private JaClassifyMapper jaClassifyMapper;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioClient client;
    @Autowired
    private JaFileMapper jaFileMapper;
    @Autowired
    private JaExcelClassifyMapper jaExcelClassifyMapper;

    @Autowired
    private ExcelReadUtils excelReadUtils;


    /**
     * 查询数据管理
     *
     * @param tableId 数据管理主键
     * @return 数据管理
     */
    @Override
    public JaDateTable selectJaDateTableByTableId(Long tableId) {
        JaDateTable jaDateTable = jaDateTableMapper.selectJaDateTableByTableId(tableId);
        List<JaClassify> jaClassifies = jaDateTableMapper.queryClassifyList(tableId);
        jaDateTable.setClassifyList(jaClassifies);
        return jaDateTable;
    }

    /**
     * 查询数据管理列表
     *
     * @param jaDateTable 数据管理
     * @return 数据管理
     */
    @Override
    public List<JaDateTable> selectJaDateTableList(JaDateTable jaDateTable) {
        List<JaDateTable> jaDateTables = jaDateTableMapper.selectJaDateTableList(jaDateTable);
        if(CollectionUtil.isNotEmpty(jaDateTables)){
            for (JaDateTable jaDateTable1 : jaDateTables) {

                List<JaClassify> jaClassifies = jaDateTableMapper.queryClassifyList(jaDateTable1.getTableId());
                if (CollectionUtil.isNotEmpty(jaClassifies)) {
                    String result = jaClassifies.stream()
                            .map(JaClassify::getName) // 提取字段
                            .collect(Collectors.joining(", ")); // 连接成字符串
                    jaDateTable1.setClassificationNames(result);
                }
                jaDateTable1.setClassifyList(jaClassifies);

                if (StringUtils.isNotEmpty(jaDateTable1.getClassificationId())) {
                    Long[] classificationIds = Convert.toLongArray(jaDateTable1.getClassificationId());
                    List<String> classificationNames = jaClassifyMapper
                            .selectJaClassifyDisplayNameByIds(Classify.DATA_TABLE_CLASSIFY, classificationIds);
                    jaDateTable1.setClassificationList(classificationNames);
                }
                if (StringUtils.isNotEmpty(jaDateTable1.getSortId())) {
                    Long[] sortIds = Convert.toLongArray(jaDateTable1.getSortId());
                    List<String> sortNames = jaClassifyMapper.selectJaClassifyNameByIds(Classify.SORT_CLASSIFY, sortIds);
                    jaDateTable1.setSortList(sortNames);
                }
            }

        }
        return jaDateTables;
    }

    /**
     * 新增数据管理
     *
     * @param jaDateTable 数据管理
     * @return 结果
     */
    @Override
    public int insertJaDateTable(JaDateTable jaDateTable) {
        jaDateTable.setCreateTime(DateUtils.getNowDate());
        int i = jaDateTableMapper.insertJaDateTable(jaDateTable);

        saveExcelClassfiy(jaDateTable);
        return i;
    }

    private void saveExcelClassfiy(JaDateTable jaDateTable) {
        String classificationIds = jaDateTable.getClassificationId();
        if (StringUtils.isNotBlank(classificationIds)) {
            String[] split = classificationIds.split(",");
            for (String classificationId : split) {
                JaExcelClassify jaExcelClassify = new JaExcelClassify();
                jaExcelClassify.setClassifyId(Long.valueOf(classificationId));
                jaExcelClassify.setExcelId(getId());
                jaExcelClassify.setTableId(jaDateTable.getTableId());
                jaExcelClassifyMapper.insertJaExcelClassify(jaExcelClassify);
            }
        }
    }

    public Long getId() {
        Random random = new Random();
        int randomNumber = random.nextInt(900000000) + 100000000;
        return Long.valueOf(randomNumber);
    }

    /**
     * 修改数据管理
     *
     * @param jaDateTable 数据管理
     * @return 结果
     */
    @Override
    public int updateJaDateTable(JaDateTable jaDateTable) {
        jaDateTable.setUpdateTime(DateUtils.getNowDate());
        jaExcelClassifyMapper.deleteJaExcelClassifyByTableId(jaDateTable.getTableId());
        saveExcelClassfiy(jaDateTable);
        return jaDateTableMapper.updateJaDateTable(jaDateTable);
    }

    /**
     * 批量删除数据管理
     *
     * @param tableIds 需要删除的数据管理主键
     * @return 结果
     */
    @Override
    public int deleteJaDateTableByTableIds(Long[] tableIds) {
        for (Long id : tableIds) {
            jaExcelClassifyMapper.deleteJaExcelClassifyByTableId(id);
        }
        return jaDateTableMapper.deleteJaDateTableByTableIds(tableIds);
    }

    /**
     * 删除数据管理信息
     *
     * @param tableId 数据管理主键
     * @return 结果
     */
    @Override
    public int deleteJaDateTableByTableId(Long tableId) {
        jaExcelClassifyMapper.deleteJaExcelClassifyByTableId(tableId);
        return jaDateTableMapper.deleteJaDateTableByTableId(tableId);
    }

    @Override
    public List<JaFile> queryExcelName(Long id) {
        List<JaFile> strings = jaDateTableMapper.queryJaDateTableByclassifId(id);
        return strings;
    }

    @Override
    public ExcelData queryExcelData(String url, String tempDir) {
        ExcelData excelData = excelReadUtils.getExcelData(url, tempDir);
        return excelData;
    }

    @Override
    public ExcelArrangeData queryExcelLine(ExcelLineVo excelLineVo) {
        log.info("queryExcelLine===开始===" + JSON.toJSONString(excelLineVo));
        ExcelArrangeData excelArrangeData = excelReadUtils
                .getExcelDataByTitle(excelLineVo.getUrl(), excelLineVo.getTitle(), "时间",
                        excelLineVo.getBegin(), excelLineVo.getEnd(), excelLineVo.getTempDir());
        excelArrangeData.setTitle(excelLineVo.getExcelName() + "-" + excelLineVo.getTitle());
        return excelArrangeData;
    }

    public Map<String, List<ExcelLineVo>> sortMapByListSize(Map<String, List<ExcelLineVo>> map) {
        return map.entrySet()
                .stream()
                .sorted(Map.Entry.<String, List<ExcelLineVo>>comparingByValue(Comparator.comparingInt(List::size)).reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, // 合并函数，如果有重复的键，这里选择第一个（可以根据需求调整）
                        LinkedHashMap::new // 使用 LinkedHashMap 保持插入顺序
                ));
    }

    public Map<String, List<ArrangeVo>> sortMapByListSize1(Map<String, List<ArrangeVo>> map) {
        return map.entrySet()
                .stream()
                .sorted(Map.Entry.<String, List<ArrangeVo>>comparingByValue(Comparator.comparingInt(List::size)).reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, // 合并函数，如果有重复的键，这里选择第一个（可以根据需求调整）
                        LinkedHashMap::new // 使用 LinkedHashMap 保持插入顺序
                ));
    }

    @Override
    public List<ExcelResult> queryExcelMoreLine(ExcelLineVo lineVo) {
        List<ExcelResult> resultList = new ArrayList<>();
        List<ExcelArrangeData> list = new ArrayList<>();
        log.info("queryExcelMoreLine====" + JSON.toJSONString(lineVo));
        if (CollectionUtil.isNotEmpty(lineVo.getLineVoList())) {
            List<ExcelLineVo> lineVoList = lineVo.getLineVoList();
            //获取excel最多的文件
            for (ExcelLineVo excelLineVo : lineVoList) {
                ExcelArrangeData excelArrangeData = excelReadUtils
                        .getExcelDataByTitle(excelLineVo.getUrl(), excelLineVo.getTitle(), "时间", excelLineVo.getBegin(),
                                excelLineVo.getEnd(), lineVo.getTempDir());
                if (excelLineVo != null) {
                    List<ArrangeVo> arrangeVoList = excelArrangeData.getArrangeVoList();
                    arrangeVoList.forEach(s -> {
                        s.setTitle(excelLineVo.getExcelName() + "-" + excelLineVo.getTitle());
                    });
                }
                excelArrangeData.setTitle(excelLineVo.getExcelName() + "-" + excelLineVo.getTitle());
                list.add(excelArrangeData);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            List<ArrangeVo> all = new ArrayList<>();
            List<String> stringList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                ExcelArrangeData excelArrangeData = list.get(i);
                List<ArrangeVo> arrangeVoList = excelArrangeData.getArrangeVoList();
                stringList.add(excelArrangeData.getTitle());
                all.addAll(arrangeVoList);
            }
            if (!CollectionUtils.isEmpty(all)) {
                Map<String, List<ArrangeVo>> collect = all.stream().collect(Collectors.groupingBy(ArrangeVo::getTime));
                //对map排序
                Map<String, List<ArrangeVo>> stringListMap = sortMapByListSize1(collect);
                for (String key : stringListMap.keySet()) {
                    //本来的数量
                    List<ArrangeVo> arrangeVos = collect.get(key);
                    if (CollectionUtils.isNotEmpty(arrangeVos) && CollectionUtils.isNotEmpty(stringList)) {
                        List<String> names = arrangeVos.stream().map(ArrangeVo::getTitle).collect(Collectors.toList());
                        List<String> collect1 = stringList.stream().filter(e -> !names.contains(e)).collect(Collectors.toList());
                        for (String str : collect1) {
                            ArrangeVo arrangeVo1 = new ArrangeVo();
                            arrangeVo1.setTime(arrangeVos.get(0).getTime());
                            arrangeVo1.setTitle(str);
                            arrangeVo1.setValue("");
                            arrangeVos.add(arrangeVo1);
                        }
                    }
                    Collections.sort(arrangeVos, Comparator.comparing(ArrangeVo::getTitle));
                }

                for (String key : stringListMap.keySet()) {
                    Map<String, List<ArrangeVo>> result = new HashMap<>();
                    ExcelResult excelResult = new ExcelResult();
                    excelResult.setYear(key);
                    result.put(key, stringListMap.get(key));
                    excelResult.setListMap(result);
                    resultList.add(excelResult);
                }
            }
        }
        return resultList;
    }

    @Override
    public Integer updateFile(JaFile jaFile) {
        JaFile jaFile1 = new JaFile();
        jaFile1.setForeignKey(jaFile.getForeignKey());
        jaFile1.setFlag("3");
        List<JaFile> jaFiles = jaFileMapper.selectJaFileList(jaFile1);
        if (CollectionUtil.isNotEmpty(jaFiles)) {
            jaFileMapper.deleteJaFile(jaFiles.get(0));
        }
        jaFileMapper.insertJaFile(jaFile);
        Long fileId = jaFile.getId();
        JaDateTable jaDateTable1 = jaDateTableMapper.selectJaDateTableByTableId(jaFile.getForeignKey());
        if (ObjectUtil.isNotEmpty(jaDateTable1)) {
            jaFileMapper.deleteJaFileById(jaFile.getForeignKey());
        }
        JaDateTable jaDateTable = new JaDateTable();
        jaDateTable.setTableId(jaFile.getForeignKey());
        jaDateTable.setFileId(fileId);
        return jaDateTableMapper.updateJaDateTable(jaDateTable);
    }
}
